package com.cet.programmercarl.algorithmperformancanalysis.哈希表;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: algorithm
 * @description: 四数和
 * @author: 陈恩涛
 * @create: 2022-03-17 11:44
 **/
public class LC18 {

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            if (i > 0 && nums[i - 1] == nums[i]) {
                continue;
            }
            for (int j = i + 1; j < length; j++) {
                if (j > i + 1 && nums[j - 1] == nums[j]) {
                    continue;
                }
                int left = j + 1;
                int right = length - 1;

                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        result.add(Arrays.asList(nums[i], nums[left], nums[right], nums[j]));
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left ++;
                        }
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    }
                }

            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] nums = {-5, -3, -8, 9, 6, -10, 9, 8, -5, 4, 8, -4, 3, 7, 4, -7, 5, 0};
        for (List<Integer> list : fourSum(nums, -6)) {
            System.out.println(list);
        }

    }
}
